package com.lenovo.mso2o.rest;

import com.lenovo.framework.entity.FGson;
import com.lenovo.framework.rest.CountingRequestBody;
import com.lenovo.framework.rest.DownloadProgressInterceptor;
import com.lenovo.framework.rest.client.OneWayAuthHttpClient;
import com.lenovo.mso2o.biz.AccountManagerImpl;
import com.lenovo.mso2o.conf.MSConstants;

import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;


public final class ServiceGenerator {

    // No need to instantiate this class.
    private ServiceGenerator() {
    }

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null, null, null, null);
    }

    public static <S> S createService(Class<S> serviceClass, String baseUrl) {
        return createService(serviceClass, baseUrl,null,null, null);
    }

    public static <S> S createService(Class<S> serviceClass, Converter.Factory factory) {
        return createService(serviceClass, null, factory, null, null);
    }

    public static <S> S createServices(Class<S> serviceClass, String baseUrl) {
        return createService(serviceClass, baseUrl, null, null, null);
    }

    public static <S> S createService(Class<S> serviceClass, CountingRequestBody.Listener uploadListener) {
        return createService(serviceClass, null, null, uploadListener, null);
    }

    public static <S> S createService(Class<S> serviceClass, DownloadProgressInterceptor.DownloadProgressListener downloadProgressListener) {
        return createService(serviceClass, null, null, null, downloadProgressListener);
    }

    public static <S> S createService(Class<S> serviceClass, String baseUrl,final Converter.Factory factory, CountingRequestBody.Listener uploadListener, DownloadProgressInterceptor.DownloadProgressListener downloadProgressListener) {

        Retrofit.Builder builder = new Retrofit.Builder()
                .baseUrl(baseUrl == null ? MSConstants.APIConstants.APISERVER_ADDRESS: baseUrl)
                .addConverterFactory(factory == null ? GsonConverterFactory.create(FGson.gson()) : factory)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(OneWayAuthHttpClient.getClient(AccountManagerImpl.instance, uploadListener, downloadProgressListener));
        Retrofit adapter = builder.build();
        return adapter.create(serviceClass);
    }

}
